/// <reference path="js/mui.min.js" />
/// <reference path="jquery.min.js" />

/*
 *  js框架
 */
void

function(global, window) {
	var $ = global.$;
	var DOC = global.document;
	var win = window;
	/*
	 * 全局变量
	 */

	Core = {
		Config: {
			ApiUrl: "https://localhost:7055/Api/",
			//ApiUrl: "http://47.113.117.255:5007/Api/",
			HostName: "http://127.0.0.1:8848/App/"
		},
		User: {
			GetUser: function() {
				var user = localStorage.getItem('User');
				if (!user)
					return user;

				user = JSON.parse(user);
				if ((Date.now() - user.LoginTime) > (user.expires * 3600000)) {
					localStorage.removeItem('User');
					return null;
				}

				return user;
			},
			SetUser: function(user) {
				if (!user)
					return;
				user.LoginTime = new Date().getTime();
				localStorage.setItem('User', JSON.stringify(user));
				localStorage.setItem('Token', user.token);
			},
			RemoveUser: function() {
				localStorage.removeItem('User');
				localStorage.removeItem('User');
			},
			IsLogin: function() {
				if (window.location.href.indexOf("login.html") > -1) {
					return true;
				}
				var user = this.GetUser();
				if (!user) {
					var that = this;
					mui.toast("登录超时");
					setTimeout(function() {
						top.window.location.href = Core.Config.HostName + "login.html";
					}, 1500);
					return false;
				}
				return true;
			},
			IsAutoLogin() {
				if (window.location.href.indexOf("login.html") == -1) {
					return;
				}
				if (!this.IsLogin()) {
					return;
				}
				var user = this.GetUser();
				if (user?.IsAutoLogin == true) {
					top.window.location.href = Core.Config.HostName + "index.html";
				}
			}
		},
		Msg: {
			Alert: function(msg, func) {
				mui.alert(msg, func);
			},
			Confirm: function(msg, title, btnArray, func) {
				title = title || "操作";
				btnArray = btnArray || ['否', '是'];
				mui.confirm(msg, func, title, btnArray, func)
			},
			Tip: function(msg) {
				mui.toast(msg);
			},
			Prompt: function(title, func) {
				var btnArray = ['取消', '确定'];
				mui.prompt('', '', title, btnArray, function(e) {
					if (e.index == 1) {
						func(e.value)
					}
				})
			}
		},
		Token: {
			GetToken: function() {
				return localStorage.getItem('Token');
			},
			SetToken: function(token) {
				localStorage.setItem('Token', token);
			},
			RemoveToken: function() {
				localStorage.removeItem('Token');
			}
		},
		Verify: {
			/*是否为空 返回true和false*/
			isnullorempty: function(str) {
				if (str == null) return true;
				if (str.length == 0) return true;
				if (/^\s*$/i.test(str)) return true;
				return false;
			},
			/*是否是带两位小数的数字 返回true和false*/
			isdemice: function(str) {
				return /^[0-9]*[\.][0-9]{0,2}$/.test(str);
			},
			/*是否是数字 返回true和false*/
			isnumber: function(str) {
				return /^[0-9]*$/.test(str);
			},
			/*判断手机号码格式 返回true和false*/
			ishone: function(str) {
				//return str.match(/^1[3|4|5|7|8|9][0-9]\d{4,8}$/);
				return /^1\d{10}$/.test(str);
			},
			/*验证邮箱格式 返回true和false*/
			isemail: function(str) {
				return str.match(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
			},
			/*验证QQ格式*/
			isqq: function(str) {
				return str.match(/^[1-9]{1}[0-9]{4,8}$/);
			},
			/*验证身份证*/
			isIDcard: function(str) {
				return str.match(
					/^[1-9]\d{5}(19\d{2}|[2-9]\d{3})((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])(\d{4}|\d{3}X)$/i);
			}
		},
		Tool: {
			QueryUrlString: function(name) {
				const reg = /(\w+)=([^&]+)/g;
				const params = {};
				let match;
				var url = window.location.href;
				while ((match = reg.exec(url)) !== null) {
					params[match[1]] = match[2];
				}
				return params;
			},
			GetUrlParam: function(name) {
				let params_str = location.search.substring(1);
				var reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, "i");
				var result = params_str.match(reg);
				if (result === null) {
					return null;
				}
				// 对编码过 URI 进行解码
				return decodeURIComponent(result[2]);
			},
			GetElemAttr: function(element, attrName) {
			    if (attrName.startsWith('data-')) {
			        if (element.dataset !== undefined) {
			            var camelCaseName = attrName.substring(5).replace(/-([a-z])/ig, function (all, letter) {
			                return letter.toUpperCase();
			            });
			            return element.dataset[camelCaseName];
			        } else {
			            return element.getAttribute(attrName);
			        }
			    } else {
			        console.warn('Non data-* custom attributes are not standard. Consider using data-* prefixes.');
			        return element.getAttribute(attrName);
			    }
			},
			Back: function(url) {
				if (url) {
					if (url.indexOf(".html") == -1)
						url += ".html";
					window.location.href = url;
				}
				window.history.back();
			},
			GetTodayDate: function(){
				const today = new Date();
				const year = today.getFullYear();
				const month = String(today.getMonth() + 1).padStart(2, '0');
				const day = String(today.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			}
		},
		Post: function(_url, _data, _success, opts) {
			var that = this;
			if (!that.User.IsLogin())
				return;

			var token = that.Token.GetToken();
			var url = that.Config.ApiUrl + _url;
			var o = $.extend({
				url: url,
				headers: {
					"Authorization": "Bearer " + token
				},
				contentType: "application/json",
				//data: _data,
				data: JSON.stringify(_data),
				dataType: "json",
				success: function(data, status, jqXHR) {
					if (data.errorMsg) {
						that.Msg.Alert(data.errorMsg);
						return;
					}
					_success && _success(data, status, jqXHR);
				},
				error: function(xhr, status, error) {
					if (xhr.status == 403) {
						that.Msg.Tip("登录超时");
						setTimeout(function() {
							top.window.location.href = Core.Config.HostName + "login.html";
						}, 1500);
					}
				},
				type: "post"
			}, opts);
			$.ajax(o);
		},
	}

	$(function() {
		if (!Core.User.IsLogin()) {
			return;
		}
		Core.User.IsAutoLogin();
	})
}(self, window);